package com.example.photongrid;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.io.*;

import android.util.Log;

public class Server implements Runnable
{

	private static final int PORT = 5500;
	public static Board board = new Board();
	public static int dirChangeSinceLastUpdate = 0;
	public static String serverip;
	private ArrayList<Socket> sockets = new ArrayList<Socket>();
	ServerSocket serverSocket ;
	ObjectInputStream in = null;
	ObjectOutputStream out = null;
	ArrayList<ServerListeningThread> slt = new ArrayList<ServerListeningThread>();
	public static int full = 0;
	
	private String getLocalIpAddress() {
	      try {
	          for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
	              NetworkInterface intf = en.nextElement();
	              for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
	                  InetAddress inetAddress = enumIpAddr.nextElement();
	                  if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
	              }
	          }
	      } catch (SocketException ex) {
	          Log.e("ServerActivity", ex.toString());
	      }
	      return null;
	  }
	@Override
	public void run() {
		if(sockets.size() < 2)
		{
			try {
				serverSocket = new ServerSocket(5590);
				System.out.println("Socket Opened");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try
			{
				
				sockets.add(serverSocket.accept());
				System.out.println("Client Connected");
				
					 slt.add(new ServerListeningThread(sockets.get(sockets.size()-1), serverSocket, sockets.size()));
					 Thread t = new Thread(slt.get(slt.size()-1));
					 t.start();
		
			}
			catch(IOException e)
			{
				System.out.println("Error occured in accepting the socket");
			}
			serverip = getLocalIpAddress();
			
		}
		else
		{
			return;
		}
	}
	
	public int getNoOfPlayers(){
		return sockets.size();
	}	 
	
	
	
	
	
	
}